import {MD5} from 'crypto-js'
import {btoa} from 'Base64'
import {keys} from 'lodash'
import {ajax} from 'jquery'
import envConfig from '../config/envConfig'

const ZSTJAppKey = 'HZ_PME_API_V1'
const ZSTJAppSecret = '1!2@3#4$5%6^'
const isEnv = process.env.NODE_ENV == 'production'

// 生成相关的验签
let Authorizations = {
    ZSTJ: function(param){      // 掌上体检APP接口验签
        var preSign = Object.assign(param, {
            secret:ZSTJAppSecret
        });
        // 1. 根据 Key 排序
        var arrKeyPreSign = keys(preSign).sort();
        var arrPreSign = {};
        arrKeyPreSign.forEach(function(key,index,arr){
            arrPreSign[key] = preSign[key];
        });
        // 2. 把对象转换为小写的字符串
        var newPreSign = JSON.stringify(arrPreSign).toLowerCase();
        // 3. 生成相关的验签
        var safeStr = unescape(encodeURIComponent(`${ZSTJAppKey}:${MD5(newPreSign)}`));
        // 4. Base64 加密
        return `Basic ${btoa(safeStr)}`;
    }
}

// 合并生成相关的URL地址
let CombineUrl = (url, type) => {
    var envObj = isEnv ? envConfig.pro : envConfig.test;
    return `${envObj[type]}${url}`;
}

export default {
    Get(url, callback, type = 'ZSTJ') {
        ajax({
          url: CombineUrl(url, type),
          type: 'GET',
          dataType: 'json',
          data: {},
          beforeSend: function (xhr) {
            //   xhr.setRequestHeader("Authorization", Authorizations[type](data));
          },
          success: function (result) {
            callback(result);
          },
          error: function (xhr, errorType, error) {
            console.dir(error);
          }
        });
    },
    Post(url, data, callback, type = 'ZSTJ') {
        data.timespan = Math.round(new Date().getTime() / 1000);
        ajax({
          url: CombineUrl(url, type),
          type: 'POST',
          contentType: 'application/json', 
          dataType: 'json',
          data: JSON.stringify(data),
          beforeSend: function (xhr) {
              xhr.setRequestHeader("Authorization", Authorizations[type](data));
          },
          success: function (result) {
            callback(result);
          },
          error: function (xhr, errorType, error) {
            console.dir(error);
          }
        });
    }
}